package com.qf.common.xxljob.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.common.xxljob.core.XxlJobInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;

@Component
public class XxlJobUtil {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.executor.appname}")
    private String appname;
    //针对第三方提供的接口，一般用RestTemplate类似的工具直接进行调用
    //类似的工具还有OkHttp/HttpClient调用
    private RestTemplate restTemplate = new RestTemplate();

    private static final String ADD_URL = "/jobinfo/addJob";
    private static final String UPDATE_URL = "/jobinfo/updateJob";
    private static final String REMOVE_URL = "/jobinfo/removeJob";
    private static final String PAUSE_URL = "/jobinfo/pauseJob";
    private static final String START_URL = "/jobinfo/startJob";
    private static final String ADD_START_URL = "/jobinfo/addAndStart";
    private static final String GET_GROUP_ID = "/jobgroup/getGroupId";


    public String add(XxlJobInfo jobInfo) {
        // 查询对应groupId:
        Map<String, Object> param = new HashMap<>();
        param.put("appname", appname);
        String json = JSON.toJSONString(param);
        String result = doPost(adminAddresses + GET_GROUP_ID, json);

        JSONObject jsonObject = JSON.parseObject(result);
        String groupId = jsonObject.getString("content");
        jobInfo.setJobGroup(Integer.parseInt(groupId));
        String json2 = JSON.toJSONString(jobInfo);
        return doPost(adminAddresses + ADD_URL, json2);
    }

    public String update(int id, String cron) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("jobCron", cron);
        String json = JSON.toJSONString(param);
        return doPost(adminAddresses + UPDATE_URL, json);
    }

    public String remove(int id) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        String json = JSON.toJSONString(param);
        return doPost(adminAddresses + REMOVE_URL, json);
    }

    public String pause(int id) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        String json = JSON.toJSONString(param);
        return doPost(adminAddresses + PAUSE_URL, json);
    }

    public String start(int id) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        String json = JSON.toJSONString(param);
        return doPost(adminAddresses + START_URL, json);
    }

    public String addAndStart(XxlJobInfo jobInfo) {
        Map<String, Object> param = new HashMap<>();
        param.put("appname", appname);
        String json = JSON.toJSONString(param);
        String result = doPost(adminAddresses + GET_GROUP_ID, json);

        JSONObject jsonObject = JSON.parseObject(result);
        String groupId = jsonObject.getString("content");
        jobInfo.setJobGroup(Integer.parseInt(groupId));
        String json2 = JSON.toJSONString(jobInfo);

        return doPost(adminAddresses + ADD_START_URL, json2);
    }

    public String doPost(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, entity, String.class);
        return stringResponseEntity.getBody().toString();
    }

    /**
     * 生成cron表达式得字符串
     * @param remindTime
     * @param repeatType
     * @return
     */
    public String generateCronExpression(LocalTime remindTime, Integer repeatType) {
        String second = "0"; // 固定为0秒
        String minute = String.valueOf(remindTime.getMinute());
        String hour = String.valueOf(remindTime.getHour());
        switch (repeatType) {
            case 1: // 一次
                return second + " " + minute + " " + hour + " * * ?";
            case 2: // 每天
                return second + " " + minute + " " + hour + " * * ?";
            default:
                throw new IllegalArgumentException("不支持的重复类型");
        }
    }
    /**
     * 根据生成得cron表达式，需要生成得时间数量和开始日期，计算出对应的未来时间点，并将他们以字符串形式返回
     * @param corn
     * @param size
     * @param startDate
     * @return
     */
    public List<String> getRecentDataByCorn(String corn, Integer size, Date startDate) {
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(corn);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            startDate = cronSequenceGenerator.next(startDate);
            list.add(sdf.format(startDate));
        }
        return list;
    }

}
